const onloadSsdk = url => {
  return new Promise((resolve, reject) => {
    let removeScript = function(scriptElement) {
      document.body.removeChild(scriptElement);
    };
    var scriptElement = document.createElement("script");
    document.body.appendChild(scriptElement);
    scriptElement.addEventListener(
      "load",
      e => {
        removeScript(scriptElement);
        resolve(e);
      },
      false
    );

    scriptElement.addEventListener(
      "error",
      e => {
        removeScript(scriptElement);
        reject(e);
      },
      false
    );
    scriptElement.src = url;
  });
};

const getSsdk = debug => {
  return new Promise(async (resolve, reject) => {
    if (
      !(
        window.__wxjs_environment === "miniprogram" ||
        window.navigator.userAgent.toLowerCase().indexOf("micromessenger") >
          -1 ||
        window.navigator.wxuserAgent
      )
    ) {
      return reject("need wechat dev");
    }

    let wxConfig = this.$store.dispatch("getWxParam", {
      url: window.location.href
    });
    console.log(wxConfig.data);
    wx.config({
      debug: ture,
      appId: wxConfig.data.appId,
      timestamp: wxConfig.data.timestamp,
      nonceStr: wxConfig.data.nonceStr,
      signature: wxConfig.data.signature,
      jsApiList: [
        "previewImage",
        "hideAllNonBaseMenuItem",
        "showMenuItems",
        "onMenuShareTimeline",
        "onMenuShareAppMessage",
        "chooseWXPay"
      ]
    });
    wx.ready(function() {
      return resolve();
    });
  });
};

export const wxSsdkOnload = debug => {
  if (window.wx) {
    return getSsdk(debug);
  }
  onloadSsdk("//res.wx.qq.com/open/js/jweixin-1.3.0.js").then(res => {
    return getSsdk(debug);
  });
};
